package com.ustc.hewei.nettyrpc2_0.common.factory;

import com.ustc.hewei.nettyrpc2_0.common.enumeration.RpcError;
import com.ustc.hewei.nettyrpc2_0.common.exception.SingletonException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
* @description: 单例工厂类
* @author hewei
* @date 2022/9/9 20:04
* @version 1.0
*/

public class SingletonFactory {
    private static final HashMap<Class, Object> singletonMap = new HashMap<>();
    private static final Logger logger = LoggerFactory.getLogger(SingletonFactory.class);

    public static <T> T getSingleton(Class<T> clazz) {
        Object obj = singletonMap.get(clazz);
        if (obj != null) return clazz.cast(obj);
        synchronized (clazz) {
            if (!singletonMap.containsKey(clazz)) {
                try {
                    T instance = clazz.newInstance();
                    singletonMap.put(clazz, instance);
                } catch (InstantiationException | IllegalAccessException e) {
                    logger.error("创建单例模式时异常 {}", clazz);
                    throw new SingletonException(RpcError.BUILD_SINGLETON_EXCEPTION, e);
                }
            }
        }
        return clazz.cast(singletonMap.get(clazz));
    }
}
